import {
  useMemo,
  useRef,
} from 'react'
import type {
  PickerValue,
  PickerColumnItem,
  PickerColumn,
  PickerValueExtend,
  PickerViewProps,
} from './type'

function normalizeColumn(
  column: PickerColumn,
): PickerColumnItem[] {
  return column.map(
    (item) => (typeof item === 'string' ? { label: item, value: item } : item),
  )
}

export function useColumnsExtend(
  rawColumns: PickerViewProps['columns'],
  value: PickerValue[],
): PickerValueExtend {
  /* 1. 缓存：静态列只算一次，函数列随 value 刷新 */
  const columnsRef = useRef<PickerValueExtend['columns'] | null>(null)

  const columns = useMemo(() => {
    const isFunction = typeof rawColumns === 'function'

    // 静态列且已缓存
    if (!isFunction && columnsRef.current) return columnsRef.current

    // 真正计算
    const c = isFunction ? rawColumns(value) : rawColumns
    const normalized = c.map((col) => normalizeColumn(col))
    columnsRef.current = normalized
    return normalized
    /* 依赖：rawColumns 必传；只有函数列才把 value 加进来 */
  }, [rawColumns, typeof rawColumns === 'function' ? value : undefined])

  /* 2. 根据当前 value 找出对应 item（始终要算，因为 value 会变） */
  const items = useMemo(
    () => value.map((v, index) => {
      const column = columns[index]
      if (!column) return null
      return column.find((item) => item.value === v) ?? null
    }),
    [columns, value],
  )

  return {
    get columns() {
      return columns
    },
    get items() {
      return items
    },
  }
}
